﻿using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Auth;
using Wicture.DbRESTFul.ObjectContainers;

namespace Wicture.QPZS.EPC.Auth
{
    public class EPCApiAuthorizationService : JwtTokenAuthorizationService
    {
        private List<ITokenAuthorizer> tokenAuthorizers;

        public EPCApiAuthorizationService()
        {
            tokenAuthorizers = AutofacContainer.Current.Resolve<IEnumerable<ITokenAuthorizer>>().ToList();
        }

        private ITokenAuthorizer GetTokenAuthorizer(string source)
        {
            if (!string.IsNullOrEmpty(source))
            {
                return tokenAuthorizers.FirstOrDefault(t => t.Source.Any(s => s.Equals(source, StringComparison.InvariantCultureIgnoreCase)));
            }
            return tokenAuthorizers.FirstOrDefault(t => t is DefaultTokenAuthorizer);
        }

        public override IdentityInfo Authenticate(ConfiguredAPI api, string token, string from)
        {
            var tokenAuthorizer = GetTokenAuthorizer(from);
            var identityInfo = tokenAuthorizer.Identify(token, from);

            return identityInfo;
        }
    }
}
